<template>
  <div class="monitorCdrpeer">
    <el-form label-position="left" :inline="true">
      <div>
        <div>
          <el-form-item class="display-in margin-r" :label="$t('public.agent')">
            <AgentSearch :module="'chat'" power="chat" ref="agentSearch" class="display-in" :disableShow="true"></AgentSearch>
          </el-form-item>
        </div>
        <div>
          <el-form-item class="display-in" :label="''">
            <el-checkbox v-model="form.status">{{$t('monitor.statusChangeSearch')}}</el-checkbox>
          </el-form-item>
        </div>
        <div v-if="!form.status">
          <el-form-item class="display-in" :label="$t('monitor.bAndETime')">
            <el-date-picker
              :id="'monitor_date' + Math.random()"
              v-model="dateStart"
              type="date"
              class="date im-time"
              size="mini"
              :placeholder="$t('report.startDate')">
            </el-date-picker>
            <el-time-select
              :id="'monitor_date' + Math.random()"
              class="time im-time"
              size="mini"
              v-model.trim="beginTime"
              :picker-options="optionsCurrent"
              :placeholder="$t('report.startTime')">
            </el-time-select>
            <el-date-picker
              :id="'monitor_date' + Math.random()"
              v-model="dateEnd"
              type="date"
              class="date im-time"
              size="mini"
              :placeholder="$t('report.endDate')">
            </el-date-picker>
            <el-time-select
              :id="'monitor_date' + Math.random()"
              class="timeim-time im-time"
              size="mini"
              v-model.trim="endTime"
              :picker-options="optionsCurrent"
              :placeholder="$t('report.endTime')">
            </el-time-select>
          </el-form-item>
        </div>
        <div v-if="form.status">
          <el-form-item class="display-in margin-r">
            <el-select v-model="form.imStatus" collapse-tags
                       :multiple="true"
                       style="width: 220px;"
                       :placeholder="$t('public.pleasePick')">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="display-in">
            <el-date-picker size="mini"
                            style="height: 32px"
                            class="date-choose"
                            v-model="form.date"
                            :id="['monitorDate1','monitorDate2']"
                            type="datetimerange"
                            :editable="false"
                            :picker-options="pickerOptions2"
                            :placeholder="$t('sms.choTimeScope')"
                            align="right">
            </el-date-picker>
          </el-form-item>
        </div>
      </div>
    </el-form>
    <div class="btn-wrap">
      <el-button class="primary_btn report_excel_btn" @click.stop="resetForm">{{$t('public.reset')}}</el-button>
      <el-button type="primary" class="primary_btn" @click.stop="searchCdrpeer">{{$t('public.search2')}}</el-button>
    </div>
    <div style="height: 20px; width: 100%">
      <affix v-show="!isImDeatil" :label="$t('monitor.seatStateLogSearchResult')"></affix>
      <BreadCrumbConfig v-show="isImDeatil" :titleArr="titleArr" @back="cancle"></BreadCrumbConfig>
    </div>
    <div class="btn-wrap" v-show="!isImDeatil">

      <el-button class="primary_btn" @click.stop="exportCdrPeer">{{$t('report.exportXls')}}</el-button>
      <el-popover
        v-show="!form.status"
        placement="bottom"
        width="540"
        trigger="hover"
      >
        <div v-html="$t('monitor.excelTip')" style="font-size: 12px; padding: 5px;line-height:20px"></div>
        <span slot="reference" class="tooltip"><el-button class="primary_btn export-detail" @click.sotp="exportDetailIm">{{$t('monitor.expoltDetailEXCEL')}}</el-button></span>
      </el-popover>
      <el-button class="primary_btn" v-on:click.stop="config" style="margin-left: 20px" v-if="configHeaderShow && (!form.status)">{{$t('report.setHeaderConfig')}}</el-button>
    </div>
    <!--下边表格展示============================================-->
    <div class="tables" v-show="!isImDeatil">
      <div class="caption">
        <Pagination
          class="fr"
          :small="true"
          :currentPage="curPage"
          :count="count"
          @turnPage="handleCurrentChange"
          :totalPage="Math.ceil(count/pageSize)"
        >
        </Pagination>
      </div>
      <!--表格===============================================-->
      <div>
        <el-table :data="tableData"
                  ref="elTable"
                  style="width: 100%"
                  class="monitor-cdr-table"
                  v-loading="tableLoading"
                  size="mini">
          <el-table-column
            v-for="(item, index) in headOptions.Config"
            v-if="item.show === true && item.name !== 'eachCustomTotalTime'"
            :key="index"
            :prop="item.name"
            :label="item.displayname">
          </el-table-column>
          <el-table-column
            v-if="!isShowImDetail"
            width="160"
            fixed="right"
            key="option"
            prop="option"
            :label="$t('monitor.operate')">
            <template slot-scope="scope">
              <el-button type="text" size="small" style="margin-right: 10px" @click.stop="exportDetail(scope.row)">{{$t('public.exportDetil')}}</el-button>
              <el-button type="text" size="small" style="margin-left: 0px" @click.stop="showConent(scope.row)">{{$t('call.queryDetail')}}</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!--表格==============================================================================-->
    </div>
    <!--点击查看  dialog 短信详情    start  ===============================================-->
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('monitor.agentStateDetailInfo')" :visible.sync="dialogCdrpeerDetailVisible" width="50%">
      <div class="shuomin">
        <strong>{{$t('monitor.tip')}}</strong>{{$t('monitor.tipContent')}}
        </div>
      <div class="caption">
        <Pagination
          class="fr"
          :small="true"
          :currentPage="pageForDetail"
          :count="countForDetail"
          @turnPage="handleCurrentDetail"
          :totalPage="Math.ceil(countForDetail/pageSize)"
        >
        </Pagination>
      </div>
      <!--表格===============================================-->
      <el-table :data="tableDataForDetail" stripe style="width: 100%" v-loading="tableLoading" size="mini">
        <el-table-column prop="agentName" :label="$t('public.agent')"></el-table-column>
        <el-table-column prop="EXTEN_TYPE_NAME" :label="$t('monitor.loginType')"></el-table-column>
        <el-table-column prop="BEGIN_TIME" :label="$t('monitor.beginTime')"></el-table-column>
        <el-table-column prop="END_TIME" :label="$t('monitor.endTime')"></el-table-column>
        <el-table-column prop="busyTimeLen" :label="$t('monitor.stateTime')"></el-table-column>
        <el-table-column prop="BUSY_TYPE_NAME" :label="$t('monitor.state')"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click.stop="dialogCdrpeerDetailVisible = false">{{$t('sms.close')}}</el-button>
      </div>
    </el-dialog>
    <!--点击查看  dialog 短信详情    end   ===============================================-->
    <header-option v-show="isShowConfig" :show="isShowConfig" :option="headOptionsShow" :type="type" @close="close"></header-option>
    <div :class="dialogShow ? 'layout-qua-bus' : 'layin-qua-bus'" class="business-qua-dialog">
      <h2 class="title">{{$t('monitor.agentDetail')}}
        <div v-show="dialogShow" class="close fr" @click="closeWindow"><i class="el-icon-close"></i></div>
      </h2>
      <div class="scroll">
        <Pagination
          class="fr"
          :small="true"
          :currentPage="curPageDD"
          :count="countDD"
          @turnPage="handleCurrentChangeDD"
          :totalPage="Math.ceil(countDD/pageSize)">
        </Pagination>
        <el-table :data="tableDataDD" style="width: 100%" v-loading="tableLoadingDD">
          <el-table-column
            v-for="(item) in detailTableHeaderD"
            v-if="item.show === true && item.name !== 'eachCustomTotalTime'"
            :key="item.name"
            :prop="item.name"
            :label="item.displayname">
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div v-if="isImDeatil" style="margin-top: 20px">
      <div class="caption">
        <Pagination
          class="fr"
          :small="true"
          :currentPage="curPageD"
          :count="countD"
          @turnPage="handleCurrentChangeD"
          :totalPage="Math.ceil(countD/pageSize)">
        </Pagination>
      </div>
      <el-table :data="tableDataD" style="width: 100%" size="mini">
        <el-table-column
          :width="item.name === 'BEGIN_TIME' || item.name === 'END_TIME' || item.name === 'loginTime' || item.name === 'logoutTime' || item.name === 'IP_MESSAGE' || item.name === 'loginIp' ? '160' : ''"
          v-if="item.name && item.name !== 'eachCustomTotalTime'"
          v-for="(item) in detailTableHeader"
          :key="item.name"
          :prop="item.name"
          :label="item.displayname">
        </el-table-column>
        <el-table-column
          fixed="right"
          :label="$t('monitor.operate')">
          <template slot-scope="scope">
            <el-button
              v-if="tableDataD[scope.$index].busyTimeLength !== 0 || tableData[scope.$index].END_TIME === null"
              type="text"
              @click.stop="showDetail(scope.row)"
              size="small">{{$t('sms.searchToLook')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
  import affix from './../../ui-modules/affix/Affix.vue'
  import {checkTime} from '@/utils/reportUtils.js'
  import {getDateTime, getCallTimeLength, getFormatDateTime, deepClone} from '@/utils/m7Utils.js'
  import Pagination from '@/components/public-modules/card/Pagination'
  import headerOption from '../report/base/headerOption'
  import BreadCrumbConfig from '@/components/ui-modules/breadCrumb/monitorBreadCrumb'
  import AgentSearch from './base/AgentSearch.vue'
  export default {
    name: 'MonitorCdrpeer',
    data () {
      return {
        isShowImDetail: false,
        options: [
          {
            value: 'login',
            label: this.$t('login.loginBtn')
          },
          {
            value: 'logout',
            label: this.$t('monitor.logout')
          },
          {
            value: 'modifySessionUpperLimit',
            label: this.$t('monitor.modifySessionUpperLimit1')
          },
          {
            value: 'claimOn',
            label: this.$t('public.online')
          },
          {
            value: 'claimOff',
            label: this.$t('public.offline')
          }
        ],
        isImDeatil: false,
        titleArr: [this.$t('monitor.onlineLog'), this.$t('monitor.agentStatusLog')],
        optionsCurrent: {
          start: '00:00',
          step: '00:30',
          end: '23:30'
        },
        rowsObj: {},
        endTime: '',
        beginTime: '',
        dateStart: '',
        dateEnd: '',
        isShowImTime: false,
        curPageDD: 1,
        tableLoadingDD: false,
        dialogShow: false,
        type: 'call_monitor_agent_status_log',
        isShowConfig: false,
        headOptionsShow: {},
        agents: [],
        phoneBars: [],
        tableDataDD: [],
        detailTableHeaderD: [
          {
            show: true,
            name: 'agentName',
            displayname: this.$t('public.agent')
          },
          {
            show: true,
            name: 'exten',
            displayname: this.$t('public.jobNumber')
          },
          {
            show: true,
            name: 'status',
            displayname: this.$t('monitor.state')
          },
          {
            show: true,
            name: 'beginTime',
            displayname: this.$t('monitor.beginTime')
          },
          {
            show: true,
            name: 'endTime',
            displayname: this.$t('monitor.endTime')
          },
          {
            show: true,
            name: 'timeLength',
            displayname: this.$t('monitor.stateTime')
          },
          {
            show: true,
            name: 'originalUpperLimit',
            displayname: this.$t('monitor.originalUpperLimit')
          },
          {
            show: true,
            name: 'sessionUpperLimitNum',
            displayname: this.$t('monitor.sessionUpperLimitNum')
          }
        ],
        detailTableHeader: [
          {
            name: 'agentName',
            displayname: this.$t('public.agent')
          },
          {
            name: 'agentNo',
            displayname: this.$t('public.jobNumber')
          },
          {
            name: 'loginTime',
            displayname: this.$t('monitor.loginTime')
          },
          {
            name: 'loginMethod',
            displayname: this.$t('monitor.loginType')
          },
          {
            name: 'loginIp',
            displayname: this.$t('monitor.loginIp')
          },
          {
            name: 'status',
            displayname: this.$t('monitor.busyType')
          },
          {
            name: 'logoutTime',
            displayname: this.$t('public.leaveTime')
          },
          {
            name: 'claimOnCount',
            displayname: this.$t('monitor.claimOnCount')
          },
          {
            name: 'claimOffCount',
            displayname: this.$t('monitor.claimOffCount')
          },
          {
            name: 'claimCustomCount',
            displayname: this.$t('monitor.customStatusNum')
          },
          {
            name: 'onlineTime',
            displayname: this.$t('monitor.onlineTime')
          },
          {
            name: 'openSessionTotalTime',
            displayname: this.$t('monitor.onlineTotalTime')
          },
          {
            name: 'closeSessionTotalTime',
            displayname: this.$t('monitor.offlineTotalTime')
          },
          {
            name: 'customSessionTotalTime',
            displayname: this.$t('monitor.customStatusTotalTime')
          }
        ],
        pickerOptions2: {
          shortcuts: [{
            text: this.$t('sms.thisOneWeek'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisOneMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: this.$t('sms.thisThreeMonth'),
            onClick (picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }]
        },
        headOptions: {
          Config: []
        },
        form: {
          status: false,
          type: 'im',
          imStatus: [],
          includeSubordinate: false,
          date: []
        },
        y: '',
        m: '',
        d: '',
        queryArry: '',
        tableLoading: false,
        tableLoadingD: false,
        tableDataD: [],
        tableData: [],
        tableDataForDetail: [],
        countD: 0,
        countDD: 0,
        curPageD: 1,
        count: 0,
        pageSize: 10,
        curPage: 1,
        pageForDetail: 1,
        countForDetail: 0,
        dialogCdrpeerDetailVisible: false,
        BEGIN_TIME_DETAIL: '',
        END_TIME_DETAIL: '',
        AGENT_DETAIL: '',
        expandId: '',
        expandObj: {},
        isZero: false
      }
    },
    inject: ['configHeaderShow'],
    methods: {
      // 关闭在线客服详情明细的浮层
      closeWindow () {
        this.dialogShow = false // 是否展示在线客服详情的明细
      },
      // 配置表头
      config () {
        let _type = 'im_monitor_agent_status_log'
        this.type = _type
        this.$store.dispatch('getReportTableHeader', _type).then((res) => {
          this.headOptionsShow = res
          this.isShowConfig = !this.isShowConfig // 是否展示表头
        })
      },
      // 关闭配置表头弹框
      close (data) {
        this.isShowConfig = false
        // 如果点击了保存，重新查询列表， 如果当前停留在啦在线客服详情 要重置回最初状态
        if (data === 'save') {
          this.isImDeatil = false
          this.search()
        }
      },
      // 点击面包屑导航 返回到查询列表的初始状态
      cancle () {
        // isImDeatil 参数是否展示在线客服详情
        this.isImDeatil = false
      },
      // 重置form表单
      resetForm () {
        this.form.status = false
        this.endTime = '23:30'
        this.beginTime = '00:00'
        this.dateStart = new Date(this.y, this.m, this.d)
        this.dateEnd = new Date(this.y, this.m, this.d)
        this.form.date = [new Date(this.y, this.m, this.d), new Date(this.y, this.m, this.d, 23, 59, 59)]
        this.form.imStatus = []
        this.form.includeSubordinate = false
        this.$refs.agentSearch.radioChange('agent')
      },
      // 处理第三层明细的数据
      handleMoreStatusData (data) {
        // row当前详情对象
        for (let i = 0; i < this.detailTableHeaderD.length; i++) {
          if (this.detailTableHeaderD[i].name === 'agentName' || this.detailTableHeaderD[i].name === 'exten') {
            this.detailTableHeaderD[i].show = false
          }
        }
        this.tableLoadingDD = true
        this.$store.dispatch('getMoreStatusLogs', data).then(res => {
          this.tableLoadingDD = false
          if (res.success) {
            let tableData = res.data || []
            this.countDD = res.count || 0
            tableData.forEach(item => {
              // 在线时长
              if (item.timeLength === 0) {
                item.timeLength = '00:00:00'
              } else {
                item.timeLength = getCallTimeLength(item.timeLength)
              }
              // 如果不是修改上线类型，修改前上线和修改后上限展示--
              if (item.status !== 'modifySessionUpperLimit') {
                item.sessionUpperLimitNum = '--'
                item.originalUpperLimit = '--'
              }
              // 登录方式
              if (item.status === 'logout') {
                item.status = this.$t('monitor.logout') // 登出
              } else if (item.status === 'login') {
                item.status = this.$t('login.loginBtn') // 登录
              } else if (item.status === 'claimOff') {
                item.status = this.$t('config.agent.busyStatus') // 关闭领取
              } else if (item.status === 'claimOn') {
                item.status = this.$t('config.agent.onlineStatus') // 开启领取
              } else if (item.status === 'modifySessionUpperLimit') {
                item.status = this.$t('monitor.modifySessionUpperLimit') + item.sessionUpperLimitNum + ')' // 最大会话上限，sessionUpperLimitNum会话上限个数
              }
            })
            this.tableDataDD = tableData
          }
        })
      },
      // 处理在线客服详情的明细
      handleGetMoreStatusLogs (rows) {
        let data = {}
        data.socketId = rows.socketId
        data.page = this.curPageDD
        data.pageSize = this.pageSize
        data.agentId = rows._id
        this.handleMoreStatusData(data)
      },
      // 导出在线客服详情明细，row参数为当前选中要导出的对象
      exportDetail (row) {
        let Query = {}
        let data = {}
        let _obj = this.handleDate()
        let message = checkTime(_obj.start, _obj.end, false, false) // 校验类型与时间
        if (message !== true) {
          this.$message.error(this.$t(message))
          return
        }
        // 为查询条件赋值
        Query.startTime = _obj.start // 开始时间
        Query.endTime = _obj.end // 结束时间
        Query.exten = row.exten // 座席工号
        Query.accountId = this.$store.state.session.user.account // 当前用户的pbx
        data.Method = 'exportMonitorImStatusLog' // 导出类型
        Query.agentName = row.agentName // 座席名称
        Query.agentId = row._id // 座席id
        data.Query = Query
        // 调用导出明细接口
        this.$store.dispatch('exportCdrPeer', data).then(() => {})
      },
      // 查看在线客服详情
      showConent (row) {
        if (row.loginCount && row.loginCount !== 0) {
          this.isImDeatil = true // 展示在线客服日志详情
          this.curPageD = 1 // 详情列表重置页码
          this.expandId = row._id
          this.expandObj = row // 存储用户当前点击的记录
          this.handleExpandImDetail(row._id) // 查询当前点击的列表的详情
        } else {
          this.rowsObj = row
          this.dialogShow = true
          this.curPageDD = 1
          this.getMoreStatusData(row)
        }
      },
      getMoreStatusData (row) {
        let _obj = this.handleDate()
        let message = checkTime(_obj.start, _obj.end, false, false) // 校验类型与时间
        if (message !== true) {
          this.$message.error(this.$t(message))
          return
        }
        let _data = {
          startTime: _obj.start,
          endTime: _obj.end,
          page: this.curPageDD,
          agentId: row._id,
          pageSize: this.pageSize
        }
        this.handleMoreStatusData(_data)
      },
      handleDate () {
        // 格式化查询日期
        let start = getDateTime(this.dateStart ? this.dateStart : '', 'date')
        let end = getDateTime(this.dateEnd ? this.dateEnd : '', 'date')
        start += (' ' + this.beginTime)
        end += (' ' + this.endTime)
        return {start: start, end: end}
      },
      showExportDetail (index, obj) {
        console.log(index)
        console.log(obj)
      },
      // 在线客服详情的明细翻页查询
      handleCurrentChangeDD (val) {
        this.curPageDD = val
        if (this.isZero) {
          this.getMoreStatusData(this.rowsObj)
        } else {
          // rowsObj 为当前在线客服详情对象
          this.handleGetMoreStatusLogs(this.rowsObj)
        }
      },
      // 处理在线客服详情数据
      handleExpandImDetail (_id) { // _id为当前选中点击的列表的id
        let data = {}
        let _obj = this.handleDate()
        let message = checkTime(_obj.start, _obj.end, false, false) // 校验类型与时间
        if (message !== true) {
          this.$message.error(this.$t(message))
          return
        }
        data.page = this.curPageD // 当前查询的页码
        data.pageSize = this.pageSize // 当前展示多少条
        data.agentId = _id // 座席ID
        data.startTime = _obj.start
        data.endTime = _obj.end
        this.tableLoadingD = true
        this.$store.dispatch('getLoginStatusLogs', data).then(res => {
          this.tableLoadingD = false
          if (res.success) {
            this.countD = res.count
            let tableDataD = res.data || []
            tableDataD.forEach(item => {
              item.agentName = this.expandObj.agentName
              item.agentNo = this.expandObj.exten
              // 在线时长
              if (item.onlineTime === 0) {
                item.onlineTime = '00:00:00'
              } else {
                item.onlineTime = getCallTimeLength(item.onlineTime)
              }
              // 开启时长
              if (item.openSessionTotalTime === 0) {
                item.openSessionTotalTime = '00:00:00'
              } else {
                item.openSessionTotalTime = getCallTimeLength(item.openSessionTotalTime)
              }
              // 自定义时长
              if (item.customSessionTotalTime === 0) {
                item.customSessionTotalTime = '00:00:00'
              } else {
                item.customSessionTotalTime = getCallTimeLength(item.customSessionTotalTime)
              }
              // 关闭时长
              if (item.closeSessionTotalTime === 0) {
                item.closeSessionTotalTime = '00:00:00'
              } else {
                item.closeSessionTotalTime = getCallTimeLength(item.closeSessionTotalTime)
              }
              // 登录状态
              if (item.status === 'offLine') {
                item.status = this.$t('monitor.offline')
              } else {
                item.status = this.$t('monitor.online')
              }
            })
            this.tableDataD = tableDataD // 在线客服详情数据
          }
        })
      },
      // 在线客服详情翻页
      handleCurrentChangeD (val) {
        this.curPageD = val
        this.handleExpandImDetail(this.expandId)
      },
      // 点击查询按钮
      searchCdrpeer () {
        this.curPage = 1
        this.isImDeatil = false
        this.search()
      },
      // 通话统计列表翻页
      handleCurrentChange (val) {
        this.curPage = val
        this.search()
      },
      // 查询在线客服统计
      search () {
        let _form = this.$refs.agentSearch.form // 获取座席组件的form对象
        // 接口参数对象
        let data = {
          page: this.curPage,
          pageSize: this.pageSize,
          includeSubordinate: _form.includeSubordinate,
          agents: _form.leaf
        }

        // 勾选 显示座席下架  座席不能为空
        if (data.includeSubordinate && data.agents.length === 0) {
          this.$message.error(this.$t('monitor.inputAgentNoToSearch'))
          return
        }
        // this.form.status如果状态为true说明查的是状态的明细
        if (this.form.status) {
          // 格式化查询日期
          let begin, end
          if (this.form.date) {
            if (this.form.date[0]) {
              begin = getFormatDateTime(this.form.date[0])
            }
            if (this.form.date[1]) {
              end = getFormatDateTime(this.form.date[1])
            }
          }
          // 开始时间或者结束时间不能为空
          if (!begin || !end) {
            this.$message.error(this.$t('monitor.timeWrongTip'))
            return
          }
          data.startTime = begin
          data.endTime = end
          data.status = this.form.imStatus
          this.handkeImStatus(data)
        } else {
          data.account = this.$store.state.session.user.account
          let _obj = this.handleDate()
          let message = checkTime(_obj.start, _obj.end, false, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
          data.reportType = 'im_monitor_agent_status_log'
          data.startTime = _obj.start
          data.endTime = _obj.end
          this.handleImAll(data)
        }
      },
      // 处理查询的状态明细
      handkeImStatus (data) {
        this.tableLoading = true
        this.$store.dispatch('getImStatusDetails', data).then(res => {
          this.tableLoading = false
          if (res.success) {
            this.isShowImDetail = true
            // row当前详情对象
            for (let i = 0; i < this.detailTableHeaderD.length; i++) {
              if (this.detailTableHeaderD[i].name === 'agentName' || this.detailTableHeaderD[i].name === 'exten') {
                this.detailTableHeaderD[i].show = true
              }
            }
            this.headOptions.Config = deepClone(this.detailTableHeaderD)
            let tableData = res.data || []
            this.count = res.count
            tableData.forEach(item => {
              // 如果不是修改上线类型，修改前上线和修改后上限展示--
              if (item.status !== 'modifySessionUpperLimit') {
                item.sessionUpperLimitNum = '--'
                item.originalUpperLimit = '--'
              }
              //              状态时长
              if (item.timeLength === 0) {
                item.timeLength = '--'
              } else {
                item.timeLength = getCallTimeLength(item.timeLength)
              }
              // 登录方式
              if (item.status === 'logout') {
                item.status = this.$t('monitor.logout') // 登出
              } else if (item.status === 'login') {
                item.status = this.$t('login.loginBtn') // 登录
              } else if (item.status === 'claimOff') {
                item.status = this.$t('public.offline') // 关闭领取
              } else if (item.status === 'claimOn') {
                item.status = this.$t('public.online') // 开启领取
              } else if (item.status === 'modifySessionUpperLimit') {
                item.status = this.$t('monitor.modifySessionUpperLimit') + item.sessionUpperLimitNum + ')' // 最大会话上限，sessionUpperLimitNum会话上限个数
              }
            })
            this.tableData = tableData
          }
        })
      },
      // 处理在线客服统计的数据
      handleImAll (data) {
        this.tableLoading = true
        data.user = {
          type: this.$store.state.session.user.type,
          moduleUsers: this.$store.state.session.user.moduleUsers
        }
        this.$store.dispatch('queryImStatusLogReport', data).then(res => {
          this.tableLoading = false
          if (res.success) {
            this.isShowImDetail = false
            let tableData = res.data || []
            this.count = res.count
            tableData.forEach(item => {
              //              在线总时长
              if (item.loginTimeLength === 0) {
                item.loginTimeLength = '00:00:00'
              } else {
                item.loginTimeLength = getCallTimeLength(item.loginTimeLength)
              }
              if (item.customSessionTotalTime === 0) {
                item.customSessionTotalTime = '00:00:00'
              } else {
                item.customSessionTotalTime = getCallTimeLength(item.customSessionTotalTime)
              }
              if (item.sessionTotalTime1 === 0) {
                item.sessionTotalTime1 = '00:00:00'
              } else {
                item.sessionTotalTime1 = getCallTimeLength(item.sessionTotalTime1)
              }
              if (item.sessionTotalTime2 === 0) {
                item.sessionTotalTime2 = '00:00:00'
              } else {
                item.sessionTotalTime2 = getCallTimeLength(item.sessionTotalTime2)
              }
              if (item.sessionTotalTime3 === 0) {
                item.sessionTotalTime3 = '00:00:00'
              } else {
                item.sessionTotalTime3 = getCallTimeLength(item.sessionTotalTime3)
              }
              if (item.sessionTotalTime4 === 0) {
                item.sessionTotalTime4 = '00:00:00'
              } else {
                item.sessionTotalTime4 = getCallTimeLength(item.sessionTotalTime4)
              }
              if (item.sessionTotalTime5 === 0) {
                item.sessionTotalTime5 = '00:00:00'
              } else {
                item.sessionTotalTime5 = getCallTimeLength(item.sessionTotalTime5)
              }
              //              开启领取会话总时长
              if (item.openSessionTotalTime === 0) {
                item.openSessionTotalTime = '00:00:00'
              } else {
                item.openSessionTotalTime = getCallTimeLength(item.openSessionTotalTime)
              }
              //              关闭领取会话总时长
              if (item.closeSessionTotalTime === 0) {
                item.closeSessionTotalTime = '00:00:00'
              } else {
                item.closeSessionTotalTime = getCallTimeLength(item.closeSessionTotalTime)
              }
            })
            this.headOptions = res.tableHeader // 在线客服的表头
            this.tableData = tableData
          }
        })
      },
      // 导出excel
      exportCdrPeer () {
        let _form = this.$refs.agentSearch.form // 获取座席组件的form对象
        let data = {}
        let Query = {
          includeSubordinate: _form.includeSubordinate,
          agents: _form.leaf
        }
        if (this.form.status) {
          // 格式化查询日期
          let begin, end
          if (this.form.date) {
            if (this.form.date[0]) {
              begin = getFormatDateTime(this.form.date[0])
            }
            if (this.form.date[1]) {
              end = getFormatDateTime(this.form.date[1])
            }
          }
          // 开始时间或者结束时间不能为空
          if (!begin || !end) {
            this.$message.error(this.$t('monitor.timeWrongTip'))
            return
          }
          Query.startTime = begin
          Query.endTime = end
          Query.status = this.form.imStatus
          data.Method = 'exportMonitorImStatusDetails'
        } else {
          let _obj = this.handleDate()
          let message = checkTime(_obj.start, _obj.end, false, false) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
          Query.startTime = _obj.start
          Query.endTime = _obj.end
          Query.reportType = 'im_monitor_agent_status_log'
          data.Method = 'exportStatusLogReport'
        }
        data.Query = Query
        this.$store.dispatch('exportCdrPeer', data).then(() => {})
      },
      // 导出在线客服详情
      exportDetailIm () {
        let _form = this.$refs.agentSearch.form // 获取座席组件的form对象
        let data = {}
        let Query = {
          includeSubordinate: _form.includeSubordinate,
          agents: _form.leaf
        }
        let _obj = this.handleDate()
        let message = checkTime(_obj.start, _obj.end, false, false) // 校验类型与时间
        if (message !== true) {
          this.$message.error(this.$t(message))
          return
        }
        Query.startTime = _obj.start
        Query.endTime = _obj.end
        Query.reportType = 'im_monitor_agent_status_log'
        Query.accountId = this.$store.state.session.user.account
        data.Method = 'exportStatusLogReportDetails'
        data.Query = Query
        this.$store.dispatch('exportCdrPeer', data).then(() => {})
      },
      // 处理在线客服查询详情
      searchDetail () {
        let data = {}
        data.BEGIN_TIME = this.BEGIN_TIME_DETAIL
        data.END_TIME = this.END_TIME_DETAIL
        data.AGENT = this.AGENT_DETAIL
        data.ACTION_TYPE = 'busy'
        data.pageSize = this.pageSize
        data.page = this.pageForDetail
        this.$store.dispatch('queryCdrPeer', data).then(res => {
          if (res.success) {
            let tableData = res.list || []
            this.countForDetail = res.count
            tableData.forEach(item => {
//              处理座席名称
              this.agents.forEach(one => {
                if (item.AGENT === one._id) {
                  item.agentName = one.displayName + '[' + one.exten + ']'
                }
              })
//              登录方式
              if (item.EXTEN_TYPE === 'Local') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.phone')
              } else if (item.EXTEN_TYPE === 'gateway') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.wangguan')
              } else if (item.EXTEN_TYPE === 'sip') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.softPhone')
              } else if (item.EXTEN_TYPE === 'none') {
                item.EXTEN_TYPE_NAME = this.$t('monitor.noPhone')
              }
//              忙碌时长
              if (item.END_TIME && item.BEGIN_TIME) {
                item.busyTimeLen = getCallTimeLength(item.TIME_LENGTH)
              } else {
                item.busyTimeLen = ''
              }
//              状态
              this.phoneBars.forEach(one => {
                if (item.BUSY_TYPE === one.PhoneBarItemId) {
                  item.BUSY_TYPE_NAME = one.PhoneBarItemName
                }
              })
            })
            this.tableDataForDetail = tableData
          }
        })
      },
      handleCurrentDetail (val) {
        this.pageForDetail = val
        this.searchDetail()
      },
      // 点击查看明细
      showDetail (rows) {
        this.rowsObj = rows
        this.dialogShow = true
        this.curPageDD = 1
        // row当前详情对象
        this.handleGetMoreStatusLogs(rows)
      }
    },
    components: {
      affix,
      Pagination,
      headerOption,
      BreadCrumbConfig,
      AgentSearch
    },
    mounted () {
      // 初始化时间段
      this.y = new Date().getFullYear()
      this.m = new Date().getMonth()
      this.d = new Date().getDate()
      this.endTime = '23:30'
      this.beginTime = '00:00'
      this.dateStart = new Date(this.y, this.m, this.d)
      this.dateEnd = new Date(this.y, this.m, this.d)
      this.form.date = [new Date(this.y, this.m, this.d), new Date(this.y, this.m, this.d, 23, 59, 59)]
      let p1 = this.$store.dispatch('getCache', {type: 'agents'})
      let p2 = this.$store.dispatch('getCache', {type: 'phoneBars'})
      let p3 = this.$store.dispatch('queryEnableWebStatus', {})
      Promise.all([p1, p2, p3]).then(([res1, res2, res3]) => {
        this.agents = res1
        this.phoneBars = res2
        let newData = []
        if (res3.success && res3.isEnableWebStatus) {
          res3.data.forEach(item => {
            newData.push({label: item.webStatusName, value: 'pcClaim' + item.webStatusId})
          })
          this.options = this.options.concat(newData)
        }
        this.search()
      })
    }
  }
</script>
<style lang="stylus" scoped>
  @import '../../../assets/common.styl';
  .monitorCdrpeer
    padding 20px
    .tip
      color $c-pink
    .im-time
      width 150px
      margin-right 10px
    .display-in
      display inline-block
    .margin-r
      margin-right 30px
    .ui-affix
      padding-bottom 0
    .btn-wrap
      padding 20px
      padding-right 0px
      text-align right
      .export-detail
        margin-left 20px
    .caption
      color $c-prompt
      height 48px
      line-height 48px
      padding-left 14px
      border 1px solid #ddd
      border-bottom none
      .fr
        padding-top 10px
        height 38px
  .shuomin
    color: $c-prompt;
    margin-bottom: 20px;
  .layout-qua-bus
    width 1000px
    background-color #fff
    transition transform 0.35s
    box-shadow 0 3px 6px rgba(0, 0, 0, .3)
    animation movelayout-bus .4s
    @keyframes movelayout-bus
      0%
        width 0px
      100%
        width 1000px
  .layin-qua-bus
    width:0px
    display none
    transition transform 0.35s
  .business-qua-dialog
    height calc(100vh - 54px)
    overflow-y auto
    position fixed
    right 0
    top 54px
    z-index 30
    box-sizing border-box
    padding 15px 20px
    .title
      line-height 20px
      padding-bottom 10px
      margin-bottom 20px
      border-bottom 1px solid $c-border2
    .close
      font-size 16px
      /*background-color #f2f2f2*/
      cursor pointer
</style>
